package com.baizhi.cmfz.service.impl;

import com.baizhi.cmfz.annotation.AddCacheAnnotation;
import com.baizhi.cmfz.annotation.DeleteCahceAnnotation;
import com.baizhi.cmfz.dao.ArticelDao;
import com.baizhi.cmfz.dao.GuruDao;
import com.baizhi.cmfz.entity.Articel;
import com.baizhi.cmfz.entity.Guru;
import com.baizhi.cmfz.service.ArticelService;
import com.baizhi.cmfz.service.CmfzElasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticelServiceImpl implements ArticelService {

	@Autowired(required = false)
	private ArticelDao articelDao;

	@Resource
	private CmfzElasService cmfzElasService;

	@Autowired(required = false)
	private GuruDao guruDao;
	@Override
	@Transactional(readOnly = true)
	@AddCacheAnnotation
	public Map selectArticelPage(int page, int limit, String name) {
		Map map = new HashMap();
		List<Articel> list = null;
		if(name!= null && !"".equals(name)){
//			name = "%"+name+"%";
			list = cmfzElasService.selectIndex(name, name);
			map.put("data",list);
			map.put("count",list.size());
			map.put("code",0);
			map.put("msg","");
		}else{

			name = null;
			int offset = (page-1)*limit;
			List<Articel> articels = articelDao.selectArticelPage(offset, limit, name);
			int coutn = articelDao.selectcoutn(name);
			list = cmfzElasService.selectIndex(name, name);
			map.put("data",articels);
			map.put("count",coutn);
			map.put("code",0);
			map.put("msg","");
		}
		return map;
	}

	@Override
	@Transactional
	@DeleteCahceAnnotation
	public Map insertArticel(Articel articel) {
		//删除索引
		cmfzElasService.deleteIndex();
		Map map = new HashMap();
		int i = articelDao.insertArticel(articel);
		if(i > 0){
			map.put("isInsert","添加成功");
		}else{
			map.put("isInsert","添加失败");
		}
		//创建索引
		cmfzElasService.createIndex();
		return map;
	}

	@Override
	@Transactional
	@DeleteCahceAnnotation
	public Map updateArticel(Articel articel) {
//		删除索引
		cmfzElasService.deleteIndex();
		Map map = new HashMap();
		int i = articelDao.updateArticel(articel);
		if (i > 0) {
			map.put("isUpdate","修改成功");
		}else {
			map.put("isUpdate","修改失败");
		}
		return map;
	}

	@Override
	@Transactional(readOnly = true)
	@AddCacheAnnotation
	public Map selectById(int id) {
		Map map = new HashMap();
		Articel articel = articelDao.selectById(id);
		List<Guru> gurus = guruDao.selectAll();
		map.put("articel",articel);
		map.put("gurus",gurus);
		return map;
	}

	@Override
	@Transactional
	@DeleteCahceAnnotation
	public Map deleteArticel(int id) {
//		删除索引
		cmfzElasService.deleteIndex();
		Map map = new HashMap();
		int i = articelDao.deleteArticel(id);
		if (i > 0) {
			map.put("isDelete","删除成功");
		}else {
			map.put("isDelete","删除失败");
		}
		return map;
	}
}
